// pages/report/report.js
let app =  getApp();
//背景音乐的地址
let musicUrl = "http://www.kynix.top:8080/fileManager-1.0-SNAPSHOT/audio/report.mp3";
let back =wx.getBackgroundAudioManager();//背景音乐控制器

var canvas;
var ctx;
const dpr = wx.getSystemInfoSync().pixelRatio;

Page({

    /**
     * Page initial data
     */
    data: {
        datas:[],
        userName: wx.getStorageSync('userName'),
        CanvasVisible:false,
        reportNum: 0,
        windowWidth: wx.getSystemInfoSync().windowWidth,
    },

    //返回按钮
    return(e) {
        //音效
        let audio = wx.createInnerAudioContext();
        audio.src = "http://www.kynix.top:8080/fileManager-1.0-SNAPSHOT/audio/click.mp3"
        audio.play();

        wx.navigateTo({
            url: './../head/head',
        });
    },

    //音乐启停控制
    controlMusic(e) {
        var that = this;
        if(app.globalData.musicController === true) {//正在播放
            back.pause();
            app.globalData.musicController = false
        }else {//正在暂停
            back.play();
            app.globalData.musicController = true
        }
    },

    //背景音乐播放控制
    backmusic(){
        player();
        function player(){
          back.title = "报告页";
          back.src = musicUrl;
          back.onEnded(() => {
            player();
          })
        }
    },

    /**
     * Lifecycle function--Called when page load
     */
    onLoad: function (options) {
        var that = this;
        //设置标题
        wx.setNavigationBarTitle({
            title: '总结报告',
        });

        //播放背景音乐
        that.backmusic();

        //获取展示数据并存入datas
        wx.request({
            url: app.globalData.urlHome + '/rep/one',
            data: {
                "openid": wx.getStorageSync('openid'),
            },
            header: {'content-type':'application/json'},
            method: 'POST',
            success: (result) => {
                that.setData({
                    datas: result.data,
                })
            },
            fail: () => {},
            complete: () => {}
        });

        //获取reportNum
        wx.request({
            url: app.globalData.urlHome + '/ach/all',
            data: {
                "openid": wx.getStorageSync('openid'),
            },
            header: {'content-type':'application/json'},
            method: 'POST',
            success: (result) => {
                let res = result.data[0];
                var count = 0;
                if(res.light === 1) {
                    count ++;
                }

                if(res.spring === 1) {
                    count ++;
                }

                if(res.defender === 1) {
                    count ++;
                }

                if(res.morning === 1) {
                    count ++;
                }

                if(res.wind === 1) {
                    count ++;
                }

                if(res.careless === 1) {
                    count ++;
                }

                if(res.thunder === 1) {
                    count ++;
                }

                that.setData({
                    reportNum: count,
                })
            },
            fail: () => {},
            complete: () => {}
        });

        that.intoCanvas();

    },

    /**
     * Lifecycle function--Called when page is initially rendered
     */
    onReady: function () {

    },

    /**
     * Lifecycle function--Called when page show
     */
    onShow: function () {

    },

    /**
     * Lifecycle function--Called when page hide
     */
    onHide: function () {

    },

    /**
     * Lifecycle function--Called when page unload
     */
    onUnload: function () {

    },

    /**
     * Page event handler function--Called when user drop down
     */
    onPullDownRefresh: function () {

    },

    /**
     * Called when page reach bottom
     */
    onReachBottom: function () {

    },

    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage: function () {
        var that = this;
        // 设置菜单中的转发按钮触发转发事件时的转发内容
        var shareObj = {
            title: "快来参加“世界地球日”答题活动，保护我们的地球，从你我做起！",// 分享的slogan
            path: '/pages/login/login',        // 分享的起始页面
            imageUrl: '',//自定义图片路径
        }
        return shareObj;
    },

    saveImg(e)
    {
        wx.showModal({
            title: '提示',
            content: '是否保存到相册？',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#000000',
            confirmText: '确定',
            confirmColor: '#3CC51F',
            success: (result) => {
                if (result.confirm) {
                    wx.showLoading({
                        title: '正在保存',
                      });
                    wx.canvasToTempFilePath({
                      canvas: canvas,
                      width:this.data.windowWidth,
                      height:1622.66/750*this.data.windowWidth,
                      success:(res)=>{
                        wx.saveImageToPhotosAlbum({
                          filePath: res.tempFilePath,
                          success:(res)=>{
            
                            wx.hideLoading({
                                success: (res) => {
                                    wx.showToast({
                                      title: '已保存到相册',
                                      icon:'success'
                                    });
            
                                },
                              });
                            
                          },
            
                          fail:(res)=>{
            
                            wx.hideLoading({
                                success: (res) => {
                                    wx.showToast({
                                      title: '图片保存失败',
                                      icon:'error'
                                    });
            
                                },
                              });
            
                          },
            
                        })
                      },
                      fail:(res)=>{
            
                      wx.hideLoading({
                        success: (res) => {
                            wx.showToast({
                              title: '出错了,请重试',
                              icon:'error'
                            })
                        },
                        });
            
                      }
                    });
                }
            },
            fail: () => {},
            complete: () => {}
        });
    },

    intoCanvas() // 调用此函数即可将页面写入(伪)到canvas
    {
      
          // 通过 SelectorQuery 获取 Canvas 节点
          this.data.CanvasVisible=true;
          wx.createSelectorQuery()
            .select('#canvas')
            .fields({
              node: true,
              size: true,
            })
            .exec(this.canvasInit.bind(this))
    },
    
    canvasInit(res) //别调用这个，看intoCanvas（）
    {
        wx.showLoading({
          title: '正在生成报告',
        })
        const width = res[0].width;
        const height = res[0].height;
    
        canvas = res[0].node;
        ctx = canvas.getContext('2d');
    
        canvas.width = width * dpr;
        canvas.height = height * dpr;
        ctx.scale(dpr, dpr);
    
        
        const img = canvas.createImage();

        img.onload = () => {
            this._img=img;
            this.canvasRender();

        }
        img.src='https://s3.bmp.ovh/imgs/2022/03/2b4015a1cf82b9a0.jpg';
        
      },
      

    canvasRender() //别调用这个，看intoCanvas（）
    {
        if(!this._img) return 1;

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        var w = this.data.windowWidth;
        var h = 1622.66/750*w;

        ctx.drawImage(this._img, 0, 0, w, h);
        ctx.fillStyle='#1C6604';
        ctx.font=`${w*0.05}px Arial`;

        ctx.fillText(this.data.userName, w*0.62, h*0.106);//用户名

        ctx.font=`${w*0.045}px Arial`;
        ctx.fillText(this.data.reportNum, w*0.325, h*0.355);//能量

        ctx.font=`${w*0.08}px Arial`;
        ctx.fillText(this.data.datas[0].time, w*0.29, h*0.41); //用时

        ctx.fillStyle='#FFF33B';
        ctx.font=`${w*0.086}px Arial`;
        ctx.fillText(this.data.datas[0].city, w*0.18, h*0.31); //城市
        
        
        ctx.font=`${w*0.1}px Arial`;
        ctx.fillText(this.data.datas[0].attribute, w*0.46, h*0.239); //属性

        wx.hideLoading({
            success: (res) => {
                // wx.showToast({
                //   title: '生成成功',
                //   icon:'success'
                // })
            },
          });
          
    },


})